<?php

class Admin_AdminController extends Zend_Controller_Action
{
	private $_params;
	private $_auth;	
    public function init(){
        $this->_params      = $this->_request->getParams();        
        $this->_auth         = new My_Auth();
        $this->view->auth    = $this->_auth;        
        $this->_auth        = $this->_auth->checkAuthentication();
        $this->view->auth   = $this->_auth;
    }
    public function indexAction(){        
        $modelAdmin  = new Admin_Model_Admin();        
        $adminList   = $modelAdmin->getAllData()->toArray();            
        $this->view->adminList = $adminList;                     
    }        
    public function addAction(){
        $form = new Admin_Form_Admin();
        $form->removeElement('avatar');
        $form->submit->setLabel('Thêm mới');
        $this->view->form = $form;                
        if ($this->getRequest()->isPost()) {            
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                
                $username   = $form->getValue('username');                
                $password   = $form->getValue('password');                
                $fullname   = $form->getValue('fullname');
                $status     = $form->getValue('status');
                
                $modelAdmin = new Admin_Model_Admin();
				if(strlen($password) < 6){
					$this->view->mess = "Mật khẩu tối thiểu 6 ký tự!!!";
                    $this->view->flag = "alert";
				}elseif($modelAdmin->getDataByUsername($username)){
					$this->view->mess = "Username đã tồn tại!!!";
                    $this->view->flag = "alert";
				}else{
					$adminId = $modelAdmin->addData($username,$password,$fullname,$status,0);
                    if($adminId){                        
                        $this->_helper->redirector('index', 'admin', 'admin');                    
                    }else{
                        $this->view->mess ="Username đã tồn tại!!!";
                        $this->view->flag = "alert";
    				    $form->populate($formData);
                    }                    
				}
            }else{
                $form->populate($formData);
            }
        }
    }
    public function editAction(){        
		$form = new Admin_Form_Admin();
		$form->submit->setLabel('Lưu thay đổi');
		$this->view->form = $form;
        
		if($this->getRequest()->isPost()){
			$formData = $this->getRequest()->getPost();
			if ($form->isValid($formData)){			 
				$dataUpdate['id']       = (int)($form->getValue('id'));
				$dataUpdate['username'] = $form->getValue('username');                
				$dataUpdate['password'] = $form->getValue('password');				
                $dataUpdate['fullname'] = $form->getValue('fullname');
                $dataUpdate['status']   = $form->getValue('status');
                                             
                $modelAdmin = new Admin_Model_Admin();
                $userCheck = $modelAdmin->getDataByUsername($dataUpdate['username']);
                if(!$userCheck || $userCheck['id'] == $dataUpdate['id']){
                    
                    $upload = new Zend_File_Transfer();
                    $files = $upload->getFileInfo();
                    if($upload->getFileName(null,false)){                        
                        $upload->setDestination(PUBLIC_PATH.'/upload/ava/');
                        $upload->addFilter('Rename', date("YmdHis-").$userCheck['id'].".".My_Service_File::getExtension($upload->getFileName(null,false)) );
                        $upload->receive();
                        unlink(PUBLIC_PATH.'/'.$userCheck['avatar']);                        
                        if($upload->getFileName(null,false)){
                            $dataUpdate['avatar'] = '/upload/ava/'.$upload->getFileName(null,false);
                        }else{
                            $dataUpdate['avatar'] = "";
                        }
                    }else $dataUpdate['avatar'] = $userCheck['avatar'];                                                                                                        
                    
				    if($dataUpdate['password']){
				        if(strlen($dataUpdate['password']) < 6){				            
				            unlink(PUBLIC_PATH.'/'.$dataUpdate['avatar']);
				            $this->view->mess = "Mật khẩu tối thiểu 6 ký tự!!!";
                            $this->view->flag = "alert";                            
                        }else{                              
                            $modelAdmin->updateData($dataUpdate['id'],$dataUpdate['username'],$dataUpdate['password'],$dataUpdate['fullname'],$dataUpdate['status'],$dataUpdate['avatar']);
                            $this->_helper->redirector('index', 'admin', 'admin');
                        }
    				}else{      				    
    				    $modelAdmin->updateData($dataUpdate['id'],$dataUpdate['username'],null,$dataUpdate['fullname'],$dataUpdate['status'],$dataUpdate['avatar']);
                        $this->_helper->redirector('index', 'admin', 'admin');
    				}
                                       
                }else{
                    $this->view->mess ="Username đã tồn tại!!!";
                    $this->view->flag = "alert";
    				$form->populate($formData);
    			}

			}else{
				$form->populate($formData);
			}
		}else{
			$dataUpdate['id'] = (int)($this->_getParam('id', 0));                            
            $modelAdmin = new Admin_Model_Admin();
			$userCheck = $modelAdmin->getDataById($dataUpdate['id']);
            if($userCheck){                                                   			
    			$this->view->userCheck = $userCheck;
    			$form->populate($userCheck->toArray());                
            }else{
                $this->_helper->redirector('index', 'admin', 'admin');
            }
		}
    }
    public function deleteAction(){
        $id = $this->_getParam('id', 0);
        $modelUser = new Admin_Model_Admin();
        $userCheck = $modelUser->getDataById($id);        
        if($userCheck){
            $this->view->userCheck = $userCheck;
            if($this->getRequest()->isPost()){
                $del = $this->getRequest()->getPost('del');
                if($del == 'Có'){                    
                    $adminId = $this->getRequest()->getPost('adminId');
                    $modelUser->deleteData($adminId);                                       
                }
                $this->_helper->redirector('index', 'admin', 'admin');
            }else{                                   
                if($this->_auth['adminId'] == $id){
                    $this->_helper->redirector('index', 'admin', 'admin');
                    exit();
                }
            }
        }
    }
    public function infoAction(){
        $form = new Admin_Form_Info();
        $form->submit->setLabel('Lưu');
        $modelUser = new Admin_Model_Admin();
        
        $this->view->form = $form;
        $userCheck = $modelUser->getDataById($this->_auth['adminId'])->toArray();
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $userName    = $form->getValue('username');
                $fullName          = $form->getValue('fullname');
    
                if($form->getValue('id')){
                    $upload = new Zend_File_Transfer();
                    $files = $upload->getFileInfo();
                    if($upload->getFileName(null,false)){                        
                        $upload->setDestination(PUBLIC_PATH.'/upload/ava/');
                        $tab= $this->_helper->gettab($upload->getFileName(null,false));
                        $upload->addFilter('Rename', date("YmdHis-").$userCheck['id'].".".$tab);
                        $upload->receive();
                        unlink(PUBLIC_PATH.'/'.$userCheck['avatar']);                        
                        if($upload->getFileName(null,false)){
                            $avatar = '/upload/ava/'.$upload->getFileName(null,false);
                        }else{
                            $avatar = "";
                        }
                    }
                    else {
                        $avatar = $userCheck['avatar'];
                    }  
                }
				$userId = $modelUser->updateProfile($this->_auth['adminId'],$userName, $fullName, $avatar);
                if($userId){
                    $this->view->flag = "success";
                    $this->view->mess = 'Đã cập nhật thông tin profile của bạn!';
                }
            }else{
                $form->populate($formData);
            }
        }else{
            
            $form->populate($userCheck);
        }
        
    }

    public function changeAction(){
        $form = new Admin_Form_Change();
        $flashHelper = $this->_helper->getHelper('FlashMessenger');
        if($this->_request->isPost()){
            $data = $this->_request->getPost();
            if($form->isValid($data)){
                $userModel = new Admin_Model_Admin();
                $userData = $userModel->getDataById($this->_auth['adminId']);
                $params['oldPassword'] = md5($form->getValue('currPass'));
                $params['newPassword'] = md5($form->getValue('newPass'));
                if($userData['password'] != $params['oldPassword']){
                    $flashHelper->addMessage('error|Bạn nhập sai password hiện tại!');
                }else{
                    $userData->password = $params['newPassword'];
                    //save new password
                    $st = $userData->save();
                    if($st){
                        $flashHelper->addMessage('success|Đổi password thành công!');
                    }else{
                        $flashHelper->addMessage('error|Có lỗi! Vui lòng thử lại sau!');
                    }
                }
                $this->_redirect('/admin/admin/change');
            }
        }
        $this->view->messages = $flashHelper->getMessages();
        $flashHelper->clearMessages();
        $this->view->form = $form;
    }
}